package ch04
{
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.text.TextField;

	/**
	 * 创建一条封闭的曲线
	 * @author jianping.shenjp
	 *
	 */
	public class MultiCurves3 extends Sprite
	{
		private var numPoints:uint=9;

		public function MultiCurves3()
		{
			init();
		}

		private function init():void
		{


			var points:Array=new Array();
			for (var i:int=0; i <numPoints; i++)
			{
				points[i]=new Object();
				points[i].x=Math.random() * stage.stageHeight;
				points[i].y=Math.random() * stage.stageHeight;
			}
			/**
			 * 首先，计算一个初始的中间点，并移动到这里。
			 * 然后，进行循环，获得每一个中间点，
			 * 最后，将最后一条曲线画回初始中间点。
			 * */
			// find the first midpoint and move to it 
			var xc1:Number=(points[0].x + points[numPoints - 1].x) / 2;
			var yc1:Number=(points[0].y + points[numPoints - 1].y) / 2;
			graphics.lineStyle(1);
			graphics.moveTo(xc1, yc1);
			drawCircle( { x: xc1, y: yc1 }, numPoints - 1 + 0.5, 0xFF0000);
			// curve through the rest, stopping at midpoints 
			for (i=0; i < points.length - 1; i++)
			{
				var xc:Number=(points[i].x + points[i + 1].x) / 2;
				var yc:Number=(points[i].y + points[i + 1].y) / 2;
				drawCircle({x: xc, y: yc}, i+0.5, 0xFF0000);
				drawCircle(points[i], i, 0xFFF000);
				graphics.curveTo(points[i].x, points[i].y, xc, yc);
			}

			// curve through the last point, back to the first midpoint 
			drawCircle(points[i], i, 0xFFF000);
			graphics.curveTo(points[i].x, points[i].y, xc1, yc1);
		}

		private function drawCircle(obj:Object, num:Number, color:uint):void
		{
			var sp:Sprite=new Sprite();
			var g:Graphics=sp.graphics;
			g.beginFill(color);
			g.drawCircle(0, 0, 3);
			sp.x=obj.x;
			sp.y=obj.y;
			g.endFill();
			this.addChild(sp);
			var txt:TextField=new TextField();
			txt.text=num + "";
			txt.x=sp.x + 3;
			txt.y=sp.y;
			this.addChild(txt);
		}
	}
}